<template>
  <div>
    <!-- 悬浮AI助教按钮 -->
    <div 
      v-if="!showChat && !isMinimized"
      class="fixed bottom-8 right-8 z-50 cursor-pointer"
      @click="openChat"
    >
      <div class="relative">
        <!-- 主按钮 -->
        <div class="w-16 h-16 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full shadow-2xl flex items-center justify-center hover:scale-110 transition-all duration-300 hover:shadow-blue-500/50">
          <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center">
            <span class="text-2xl">🤖</span>
          </div>
        </div>
        
        <!-- 脉冲动画 -->
        <div class="absolute inset-0 w-16 h-16 bg-gradient-to-br from-blue-400 to-purple-500 rounded-full animate-ping opacity-20"></div>
        
        <!-- 状态指示器 -->
        <div 
          class="absolute -top-1 -right-1 w-6 h-6 rounded-full border-2 border-white flex items-center justify-center"
          :class="{
            'bg-green-500': aiServiceStatus === true,
            'bg-yellow-500': aiServiceStatus === null,
            'bg-red-500': aiServiceStatus === false
          }"
        >
          <div 
            class="w-2 h-2 bg-white rounded-full"
            :class="{ 'animate-pulse': aiServiceStatus !== false }"
          ></div>
        </div>
        
        <!-- 提示文字 -->
        <div class="absolute -top-12 right-0 bg-gray-800 text-white px-3 py-2 rounded-lg text-sm whitespace-nowrap opacity-0 hover:opacity-100 transition-opacity duration-300">
          <div class="flex items-center gap-2">
            <span>智能AI助教</span>
            <span 
              :class="{
                'text-green-400': aiServiceStatus === true,
                'text-yellow-400': aiServiceStatus === null,
                'text-red-400': aiServiceStatus === false
              }"
            >●</span>
          </div>
          <div class="text-xs text-gray-300 mt-1">
            {{ aiServiceStatus === true ? '在线服务' : aiServiceStatus === false ? '服务离线' : '连接中...' }}
          </div>
          <div class="absolute top-full right-4 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-gray-800"></div>
        </div>
      </div>
    </div>

    <!-- 聊天界面 -->
    <div 
      v-if="showChat"
      class="fixed inset-0 z-50"
    >
      <!-- 背景遮罩 -->
      <div class="absolute inset-0 bg-black bg-opacity-30" @click="closeChat"></div>
      
      <!-- 主页面容器 -->
      <div class="relative w-full h-full flex">
        <!-- 左侧页面区域 -->
        <div class="flex-1 transition-transform duration-300" :class="showChat ? '-translate-x-1/4' : ''">
          <div class="w-full h-full">
            <!-- 这里会显示当前页面内容 -->
          </div>
        </div>
        
        <!-- AI助教聊天区域 -->
        <div class="w-1/4 h-full bg-white shadow-2xl flex flex-col overflow-hidden transition-transform duration-300" :class="showChat ? 'translate-x-0' : 'translate-x-full'">
          <!-- 聊天头部 -->
        <div class="bg-gradient-to-r from-blue-500 to-purple-600 text-white p-4 flex items-center justify-between">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-white rounded-full flex items-center justify-center">
              <span class="text-xl">🤖</span>
            </div>
            <div>
              <h3 class="font-semibold">智能AI助教</h3>
              <p class="text-sm text-blue-100">
                {{ aiServiceStatus === true ? '在线 • 随时为您服务' : aiServiceStatus === false ? '离线 • 服务暂不可用' : '连接中 • 请稍候' }}
              </p>
            </div>
          </div>
          <div class="flex items-center gap-2">
            <button 
              @click="toggleMinimize"
              class="w-8 h-8 rounded-full bg-white bg-opacity-20 hover:bg-opacity-30 flex items-center justify-center transition-all"
            >
              <span class="text-sm">−</span>
            </button>
            <button 
              @click="closeChat"
              class="w-8 h-8 rounded-full bg-white bg-opacity-20 hover:bg-opacity-30 flex items-center justify-center transition-all"
            >
              <span class="text-sm">×</span>
            </button>
          </div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50" ref="messageContainer">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="space-y-4">
            <!-- 时间戳 -->
            <div class="flex justify-center">
              <div class="bg-gray-200 text-gray-600 px-3 py-1 rounded-full text-xs">
                {{ formatTime(new Date()) }}
              </div>
            </div>
            
            <div class="flex items-start gap-3">
              <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center flex-shrink-0">
                <span class="text-sm text-white">🤖</span>
              </div>
              <div class="flex-1">
                <div class="bg-white rounded-2xl rounded-tl-md px-4 py-3 shadow-sm max-w-xs">
                  <p class="text-gray-800 text-sm">您好！我是您的智能AI助教，很高兴为您服务！</p>
                </div>
                <div class="bg-white rounded-2xl rounded-tl-md px-4 py-3 shadow-sm max-w-xs mt-2">
                  <p class="text-gray-800 text-sm">我可以帮您：</p>
                  <ul class="text-gray-600 text-sm mt-1 space-y-1">
                    <li>• 解答学习问题</li>
                    <li>• 推荐学习资源</li>
                    <li>• 制定学习计划</li>
                    <li>• 提供技术支持</li>
                    <li>• 代码审查和优化</li>
                  </ul>
                </div>
              </div>
            </div>

            <!-- 快捷回复按钮 -->
            <div class="flex items-start gap-3">
              <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center flex-shrink-0">
                <span class="text-sm text-white">🤖</span>
              </div>
              <div class="flex-1">
                <div class="bg-white rounded-2xl rounded-tl-md px-4 py-3 shadow-sm">
                  <p class="text-gray-800 text-sm mb-3">您可以选择以下快捷问题：</p>
                  <div class="flex flex-wrap gap-2">
                    <button 
                      v-for="quickReply in quickReplies"
                      :key="quickReply"
                      @click="sendQuickReply(quickReply)"
                      :disabled="isSending"
                      class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-xs hover:bg-blue-200 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {{ quickReply }}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 用户消息 -->
          <template v-for="(message, index) in messages" :key="message.id">
            <!-- 时间戳 -->
            <div v-if="getMessageTimestamp(message, index)" class="flex justify-center">
              <div class="bg-gray-200 text-gray-600 px-3 py-1 rounded-full text-xs">
                {{ getMessageTimestamp(message, index) }}
              </div>
            </div>
            
            <div class="flex items-start gap-3" :class="message.sender === 'user' ? 'flex-row-reverse' : ''">
              <div 
                class="w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0"
                :class="message.sender === 'user' ? 'bg-gradient-to-br from-green-500 to-blue-500' : 'bg-gradient-to-br from-blue-500 to-purple-600'"
              >
                <span class="text-sm text-white">
                  {{ message.sender === 'user' ? '👤' : '🤖' }}
                </span>
              </div>
              <div class="flex-1" :class="message.sender === 'user' ? 'text-right' : ''">
                <div 
                  class="rounded-2xl px-4 py-3 shadow-sm max-w-xs inline-block"
                  :class="message.sender === 'user' ? 'bg-green-500 text-white rounded-tr-md' : 'bg-white text-gray-800 rounded-tl-md'"
                >
                  <p class="text-sm">
                    {{ message.content }}
                    <!-- 流式输出时显示打字光标 -->
                    <span v-if="message.isStreaming" class="typing-cursor animate-pulse">|</span>
                  </p>
                </div>
              </div>
            </div>
          </template>

          <!-- 输入中状态 -->
          <div v-if="isTyping" class="flex items-start gap-3">
            <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full flex items-center justify-center flex-shrink-0">
              <span class="text-sm text-white">🤖</span>
            </div>
            <div class="flex-1">
              <div class="bg-white rounded-2xl rounded-tl-md px-4 py-3 shadow-sm w-20">
                <div class="flex space-x-1">
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="border-t border-gray-200 p-4 bg-white">
          <div class="flex items-end gap-3">
            <div class="flex-1">
              <textarea
                v-model="newMessage"
                @keydown.enter.prevent="sendMessage"
                :disabled="isSending"
                placeholder="输入您的问题..."
                class="w-full border border-gray-300 rounded-2xl px-4 py-3 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
                rows="1"
                ref="messageInput"
              ></textarea>
            </div>
            <button 
              @click="sendMessage"
              :disabled="!newMessage.trim() || isSending"
              class="w-10 h-10 bg-gradient-to-r from-blue-500 to-purple-600 text-white rounded-full flex items-center justify-center hover:scale-105 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span class="text-lg">➤</span>
            </button>
          </div>
          
          <!-- 功能按钮 -->
          <div class="flex items-center justify-between mt-3">
            <div class="flex items-center gap-2">
              <button class="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center transition-colors">
                <span class="text-sm">📎</span>
              </button>
              <button class="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center transition-colors">
                <span class="text-sm">📷</span>
              </button>
              <button class="w-8 h-8 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center transition-colors">
                <span class="text-sm">🎤</span>
              </button>
            </div>
            <div class="flex items-center gap-2">
              <button 
                @click="clearChat"
                class="text-xs text-gray-500 hover:text-gray-700 transition-colors"
              >
                清空聊天
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

    <!-- 最小化状态 -->
    <div 
      v-if="isMinimized"
      class="fixed bottom-8 right-8 z-50 cursor-pointer"
      @click="restoreChat"
    >
      <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-full shadow-lg flex items-center justify-center hover:scale-110 transition-all duration-300">
        <span class="text-lg">💬</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, watch } from 'vue'
import aiApiService from '../api/ai.js'

// 定义事件
const emit = defineEmits(['toggle'])

// 响应式数据
const showChat = ref(false)
const isMinimized = ref(false)
const newMessage = ref('')
const messages = ref([])
const isTyping = ref(false)
const messageContainer = ref(null)
const messageInput = ref(null)
const aiServiceStatus = ref(null) // AI服务状态：null-检查中, true-可用, false-不可用

// 快捷回复
const quickReplies = ref([
  '如何开始学习？',
  '推荐学习资源',
  '制定学习计划',
  '技术问题咨询',
  '课程推荐'
])

// 方法
const openChat = () => {
  showChat.value = true
  isMinimized.value = false
  emit('toggle', true)
  nextTick(() => {
    scrollToBottom()
    messageInput.value?.focus()
  })
}

const closeChat = () => {
  showChat.value = false
  isMinimized.value = false
  emit('toggle', false)
}

const toggleMinimize = () => {
  isMinimized.value = true
  showChat.value = false
}

const restoreChat = () => {
  isMinimized.value = false
  showChat.value = true
  emit('toggle', true)
  nextTick(() => {
    scrollToBottom()
    messageInput.value?.focus()
  })
}

// 防重复发送标志
const isSending = ref(false)

const sendMessage = async () => {
  if (!newMessage.value.trim()) return
  
  // 防重复提交检查
  if (isSending.value) {
    console.log('⚠️ 正在发送消息，跳过重复请求')
    return
  }
  
  isSending.value = true
  
  const userMessage = {
    id: Date.now(),
    sender: 'user',
    content: newMessage.value,
    time: new Date()
  }
  
  messages.value.push(userMessage)
  const userInput = newMessage.value
  newMessage.value = ''
  
  // 滚动到底部
  await nextTick()
  scrollToBottom()
  
  // 先添加一个空的AI消息占位符
  const aiMessageIndex = messages.value.length
  const aiMessage = {
    id: Date.now() + 1,
    sender: 'ai',
    content: '', // 开始时为空，将逐步填充
    time: new Date(),
    isStreaming: true // 标记为正在流式输出
  }
  
  messages.value.push(aiMessage)
  await nextTick()
  scrollToBottom()
  
  try {
    console.log('🌊 [Web AI] 发送流式消息给AI:', userInput)
    
    // 使用流式发送方法
    await aiApiService.sendMessageStream(userInput, (partialContent, isComplete) => {
      // 更新AI消息的内容
      if (messages.value[aiMessageIndex]) {
        messages.value[aiMessageIndex].content = partialContent
        messages.value[aiMessageIndex].isStreaming = !isComplete
        
        // 每次更新后滚动到底部
        nextTick(() => scrollToBottom())
      }
    })
    
    console.log('🎉 [Web AI] 流式回答完成')
    
  } catch (error) {
    console.error('❌ [Web AI] 流式消息发送失败:', error)
    // 更新AI消息为错误内容
    if (messages.value[aiMessageIndex]) {
      messages.value[aiMessageIndex].content = `抱歉，我暂时无法为您提供回复。${aiApiService.getErrorMessage(error)}`
      messages.value[aiMessageIndex].isStreaming = false
    }
  } finally {
    // 无论成功还是失败，都重置发送状态
    isSending.value = false
    console.log('💡 发送状态已重置')
  }
}

const sendQuickReply = (reply) => {
  // 防重复提交检查
  if (isSending.value) {
    console.log('⚠️ 正在发送消息，跳过快捷回复重复请求')
    return
  }
  
  newMessage.value = reply
  sendMessage()
}

const clearChat = () => {
  messages.value = []
}

const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

const formatTime = (time) => {
  return time.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// 检查是否需要显示时间戳
const shouldShowTimestamp = (currentMessage, previousMessage) => {
  if (!previousMessage) return true
  
  const timeDiff = currentMessage.time - previousMessage.time
  const twoMinutes = 2 * 60 * 1000 // 2分钟转换为毫秒
  
  return timeDiff > twoMinutes
}

// 获取消息的时间戳显示
const getMessageTimestamp = (message, index) => {
  if (index === 0) return formatTime(message.time)
  
  const previousMessage = messages.value[index - 1]
  if (shouldShowTimestamp(message, previousMessage)) {
    return formatTime(message.time)
  }
  
  return null
}

// 注：AI回复现在使用流式输出，不再需要单独的回复生成函数

// 监听消息变化，自动滚动
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
})

// 检查AI服务状态
const checkAiServiceStatus = async () => {
  try {
    console.log('🔍 [Web AI] 检查AI服务状态...')
    const isHealthy = await aiApiService.checkHealth()
    aiServiceStatus.value = isHealthy
    console.log(`✅ [Web AI] AI服务状态: ${isHealthy ? '在线' : '离线'}`)
  } catch (error) {
    console.warn('⚠️ [Web AI] AI服务状态检查失败:', error)
    aiServiceStatus.value = false
  }
}

// 组件挂载时初始化
onMounted(async () => {
  // 检查AI服务状态
  await checkAiServiceStatus()
  
  // 可以在这里加载历史消息
})
</script>

<style scoped>
/* 自定义滚动条 */
.overflow-y-auto::-webkit-scrollbar {
  width: 4px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #cbd5e0;
  border-radius: 2px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #a0aec0;
}

/* 脉冲动画 */
@keyframes ping {
  75%, 100% {
    transform: scale(2);
    opacity: 0;
  }
}

.animate-ping {
  animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;
}

/* 弹跳动画 */
@keyframes bounce {
  0%, 100% {
    transform: translateY(-25%);
    animation-timing-function: cubic-bezier(0.8, 0, 1, 1);
  }
  50% {
    transform: none;
    animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
  }
}

.animate-bounce {
  animation: bounce 1s infinite;
}

/* 打字光标样式 */
.typing-cursor {
  color: #3b82f6;
  font-weight: bold;
  margin-left: 2px;
}

/* 脉冲动画 */
.animate-pulse {
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.3;
  }
}
</style>
